﻿Class TaksitDagitimi : Inherits Process

	Public Borc As New List(Of Decimal)
	Public WithEvents Grid As Grid
	Dim FirstDate, LastDate As Date

	Public Overrides Sub GenericEvent(e As ProcessEventArgs)
		Select Case e.EventType
			Case EventType.Initialize
				Start("Taksit dağılımı", "Taksitlerin ödeneceği ayları belirleyin.")
				AddList()
				CustomSize = New Size(750, 420)
			Case EventType.Shown
				Grid = List
				Grid.RowHeadersWidth = 50
				Grid.RowHeadersVisible = True
				Grid.AddColumns("01(Ocak;c;5%),02(Şubat;c;5%),03(Mart;c;5%),04(Nisan;c;5%),05(Mayıs;c;5%),06(Haziran;c;5%)")
				Grid.AddColumns("07(Temmuz;c;5%),08(Ağustos;c;5%),09(Eylül;c;5%),10(Ekim;c;5%),11(Kasım;c;5%),12(Aralık;c;5%)")
				Grid.CellBorderStyle = DataGridViewCellBorderStyle.Single
				Grid.SelectionMode = DataGridViewSelectionMode.CellSelect
				Grid.Sortable = False
				Grid.RowTemplate.Height = 48
				Grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
				List.AddButton("oto", "Otomatik dağıt")
				'List.AddButton("-", "-")
				List.AddButton("add", "Dönem ekle")
				'List.AddButton("-", "-")
				List.AddButton("remove", "Dönem çıkar")
				FirstDate = New Date(Today.AddMonths(1).Year, Today.AddMonths(1).Month, 1)
				LastDate = FirstDate.AddMonths(35)
				If LastDate > "2015/03/01" Then LastDate = "2015/03/01"
				For i As Integer = 2011 To 2015
					List.AddRow("")
					Dim Row = Grid.Rows(Grid.Rows.Count - 1)
					Row.HeaderCell.Value = i
					Row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
					For j = 1 To 12
						Dim M = i & Format(j, "00")
						If M < FirstDate.ToString("yyyyMM") Or M > LastDate.ToString("yyyyMM") Then Row.Cells(j - 1).Value = "x"
					Next
				Next
				Buttons.Show("Back.Next")
			Case EventType.Other
				Select Case e.Name
					Case "List.oto"
						If Not Confirm("Borç otomatik olarak 36 aya dağıtılacak. Devam etmek istiyor musunuz?") Then Return
						Dim MD As Integer = DateDiff(DateInterval.Month, FirstDate, LastDate) + 1
						Dim Interval = If(Borc.Count = 1, 1, (MD - 1) / (Borc.Count - 1))
						For i = 0 To MD - 1
							TaksitCount(FirstDate.AddMonths(i)) = 0
						Next
						Dim c As Decimal = 0
						For i = 0 To Borc.Count - 1
							TaksitCount(FirstDate.AddMonths(Math.Round(c))) += 1
							c += Interval
						Next
						Recalculate()
					Case "List.add"
						SetCellValue("+")
					Case "List.remove"
						SetCellValue("-")
				End Select
			Case EventType.Save
				Dim Taksitler As New SortedList(Of Date, Integer)
				Dim c As Integer = 0
				For Each Row As DataGridViewRow In Grid.Rows
					For Each Cell As DataGridViewCell In Row.Cells
						If Val(Cell.Value) > 0 Then
							Taksitler.Add(New Date(Row.HeaderCell.Value, Cell.ColumnIndex + 1, 1), Cell.Value)
							c += Val(Cell.Value)
						End If
					Next
				Next
				If c < Borc.Count Then Warning("Tüm dönemleri girmediniz. Kalan " & (Borc.Count - c) & " dönemi girdikten sonra kaydedebilirsiniz.") : Return
				If Not Confirm("Ödeme planı kaydedilecek. Devam etmek istediğinize emin misiniz?") Then Return
				CType(Caller, Object).Kaydet(Taksitler)
		End Select
	End Sub

	Property TaksitCount(d As Date) As Integer
		Get
			Dim Cell = Grid.Rows(d.Year - 2011).Cells(d.Month - 1)
			Return Val(Cell.Value)
		End Get
		Set(Value As Integer)
			Dim Cell = Grid.Rows(d.Year - 2011).Cells(d.Month - 1)
			Cell.Value = If(Value = 0, "", Trim(Value))
		End Set
	End Property

	Private Sub Grid_CellPainting(sender As Object, e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles Grid.CellPainting
		If e.RowIndex >= 0 And e.ColumnIndex >= 0 Then
			Dim R As Rectangle = e.CellBounds
			Dim Font As New Font(Me.Font.Name, Me.Font.Size - 2)
			e.Graphics.FillRectangle(Brushes.White, R)
			R.Inflate(-1, -1)
			R.Width += 1 : R.Height += 1
			e.Graphics.FillRectangle(SystemBrushes.ButtonShadow, R)
			R.Inflate(-1, -1)
			If e.FormattedValue = "x" Then
				e.Graphics.FillRectangle(New Drawing2D.HatchBrush(Drawing2D.HatchStyle.LightUpwardDiagonal, Color.DarkGray, Color.White), R)
			Else
				e.Graphics.FillRectangle(Brushes.White, R)
			End If
			If (e.State And DataGridViewElementStates.Selected) > 0 Then e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(128, SystemColors.Highlight)), R)
			If e.FormattedValue <> "x" Then
				R.Inflate(-3, -3)
				e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.ClearTypeGridFit
				Dim Text As String = Fm(Grid.Rows(e.RowIndex).Cells(e.ColumnIndex).Tag)
				If Val(e.Value) > 1 Then Text &= vbCrLf & "(" & e.Value & " dönem)"
				e.Graphics.DrawString(Text, Font, Brushes.Black, R, StrFormat("mr"))
			End If
			e.Handled = True
		End If
	End Sub

	Sub SetCellValue(d As String)
		If Grid.CurrentCell.Value = "x" Then
			Warning("Bu tarihe taksit koyamazsınız.")
			Return
		End If
		If d = " " Then
			Grid.CurrentCell.Value = If(Grid.CurrentCell.Value = "", "1", "")
		ElseIf d = "+" Then
			Grid.CurrentCell.Value = Trim(Val(Grid.CurrentCell.Value) + 1)
		ElseIf d = "-" Then
			Grid.CurrentCell.Value = If(Val(Grid.CurrentCell.Value) > 0, Trim(Val(Grid.CurrentCell.Value) - 1), "")
		Else
			Grid.CurrentCell.Value = d
		End If
		Recalculate()
	End Sub

	Sub Recalculate()
		Dim c As Integer = 0
		For Each Row As DataGridViewRow In Grid.Rows
			For Each Cell As DataGridViewCell In Row.Cells
				If Cell.Value = "" Then
					Cell.Tag = ""
				Else
					Cell.Tag = 0
					For i = 1 To Val(Cell.Value)
						If c < Borc.Count Then Cell.Tag += Borc(c)
						c += 1
					Next
				End If
			Next
		Next
		Grid.Invalidate()
	End Sub

	Private Sub Grid_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Grid.KeyDown
		If e.KeyCode = Keys.Space Then
			SetCellValue(" ")
			e.Handled = True
		ElseIf e.KeyCode = Keys.Add Then
			SetCellValue("+")
			e.Handled = True
		ElseIf e.KeyCode = Keys.Subtract Then
			SetCellValue("-")
			e.Handled = True
		End If
	End Sub

End Class